<script setup lang="ts">
import type { EChartsOption } from 'echarts';

import { onMounted, onUnmounted, ref, watch } from 'vue';

import * as echarts from 'echarts';

interface ChartProps {
    chartData: {
        name: string; // 数据名称
        value: number; // 数据值
    }[];
}

const props = defineProps<ChartProps>();

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

const getOptions = (): EChartsOption => ({
    backgroundColor: 'transparent',
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    grid: {
        top: '12%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
    },
    legend: {
        orient: 'vertical',
        left: '80%',
        textStyle: {
            color: '#fff',
        },
    },
    series: [
        {
            name: '数据统计',
            type: 'pie',
            radius: [20, 80],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
                borderRadius: 5
            },
            data: props.chartData,
        },
    ],
});

// 初始化图表
const initChart = () => {
    if (!chartRef.value) return;
    chart = echarts.init(chartRef.value);
    chart.setOption(getOptions());
};

// 监听数据变化
watch(
    () => props.chartData,
    () => {
        chart?.setOption(getOptions());
    },
    { deep: true },
);

// 监听窗口大小变化
const handleResize = () => {
    chart?.resize();
};

onMounted(() => {
    initChart();
    window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    chart?.dispose();
});
</script>

<template>
    <div ref="chartRef" style="width: 100%; height: 260px"></div>
</template>